package task

import (
	"io"
	"regexp"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type UserInfoAndRatingTask struct {
	TaskBase
}
type userInfo struct {
	Legendary     string
	Country       string
	City          string
	Name          string
	Handle        string
	University    string
	Rating        string
	MaxRating     string
	Contribution  string
	LastVisit     string
	Registered    string
	RatingHistory []ratingHistory
}

type ratingHistory struct {
	TimeStamp string
	Rating    string
	Rank      string
}

func (u *UserInfoAndRatingTask) GetParseFunc(r io.Reader) interface{} {

	doc, err := goquery.NewDocumentFromReader(r)
	if err != nil {
		u.SetErr(err)
		return ""
	}
	infoRoot := doc.Find(".main-info")
	infoStruct := userInfo{
		Legendary:    infoRoot.Find("div").Eq(0).Children().Text(),
		Country:      infoRoot.Find("div").Eq(1).Find("a").Eq(1).Text(),
		City:         infoRoot.Find("div").Eq(1).Find("a").Eq(0).Text(),
		Name:         strings.Split(infoRoot.Find("div").Eq(1).Find("div").Eq(0).Text(), ",")[0],
		University:   infoRoot.Find("div").Eq(1).Find("div").Eq(1).Find("a").Text(),
		Handle:       infoRoot.Find("h1 a").Text(),
		Rating:       doc.Find("div.info ul li span.user-legendary").Eq(0).Text(),
		MaxRating:    doc.Find("div.info ul li span.user-legendary").Eq(2).Text(),
		Contribution: doc.Find("div.info ul li").Eq(1).Find("span").Text(),
		LastVisit:    doc.Find("div.info ul li").Eq(3).Find("span").Text(),
		Registered:   doc.Find("div.info ul li").Eq(4).Find("span").Text(),
	}

	rHistoy := make([]ratingHistory, 0, 16)
	jsText := doc.Find("script").Text()
	reg, _ := regexp.Compile(`unrated.push\(\[([0-9]|,| )*\]\)`)
	ss := reg.FindAllString(jsText, -1)
	for _, s := range ss {
		st := strings.Split(s, "[")[1]
		st = strings.Split(st, "]")[0]
		st = strings.ReplaceAll(st, " ", "")
		sts := strings.Split(st, ",")
		uHis := ratingHistory{
			sts[0],
			sts[1],
			sts[2],
		}
		rHistoy = append(rHistoy, uHis)
	}
	infoStruct.RatingHistory = rHistoy
	return infoStruct
}
func NewUserInfoAndRatingTask(userHandle string) ITask {
	return &UserInfoAndRatingTask{TaskBase{url: "https://codeforces.com/profile/" + userHandle + "?graphType=rated", retryTimes: 3}}
}
